//package wmmd.disc.webmaster;

import java.io.*;
import javax.servlet.*;
import java.sql.*;
import javax.servlet.http.*;
import db.DatabaseConnector;

public class PostForm extends HttpServlet {
    
    //----------------------------------------------------------------------------------------
    /**
     * Called by postform.jsp; processes the New Topic form data and inserts the topic into
     * the appropriate database.
     */
    
//doPost method included for POST requests
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        doGet(request, response);
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        String tablename = request.getParameter("tName");

        int lRTID = 0;
        
        //Variables for the database connection
        DatabaseConnector con1 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        DatabaseConnector con2 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        DatabaseConnector con3 = new DatabaseConnector(DatabaseConnector.getDatabaseType());

        ResultSet rs = null;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {
            
            //Grab the topic ID, and then convert it to int
            String RTID_string = request.getParameter("RTID");
            lRTID = Integer.valueOf(RTID_string).intValue();
            
            //Variables for all of the values we need to update the db.
            //Note: a variable for date has not been included; the db automatically assigns
            //today's date to a new record.
            int pTopic = 0;
            int pTLevel = 0;
            int pResponses = 0;
            double pResponseID = 0;
            int lTopic = 0;
            int lParent = 0;
            double lResponseID = 0;
            int lTLevel = 0;
            int lResponses = 0;
            String lName = "";
            String lSubject = "";
            String lMessage = "";
            
            //If the message starts a new topic, set it up accordingly
            if(lRTID < 1) {

                //TODO: Query
                String SQL = "SELECT Topic FROM " + tablename + " ORDER BY Topic DESC";
                rs = con1.selectSQL_RS(SQL);

                rs.next();
                pTopic = Integer.valueOf(rs.getString("Topic")).intValue();

                lTopic = pTopic + 1;
                lResponseID = lTopic;
                lName = request.getParameter("NAME");
                lSubject = request.getParameter("SUBJECT");
                lMessage = request.getParameter("MESSAGE");
            } else {  //Otherwise, the message is a response to a previous topic

                String SQL = "SELECT Topic,ResponseID,TLevel,Responses FROM " + tablename + " WHERE ID = ?";
                String[][] rs1 = con1.selectSQL(SQL,4,new Object[]{RTID_string});

                for (int i=0;i<rs1.length;i++){
                    pTopic = Integer.valueOf(rs1[i][0]).intValue();
                    pResponseID = Double.valueOf(rs1[i][1]).doubleValue();
                    pTLevel = Integer.valueOf(rs1[i][2]).intValue();
                    pResponses = Integer.valueOf(rs1[i][3]).intValue();
                }
                
                //Manipulate & assign the needed variables
                lTLevel = pTLevel + 1;
                lTopic = pTopic;
                lParent = Integer.valueOf(request.getParameter("RTID")).intValue();
                lResponseID = pResponseID + (pResponses + 1) * (Math.pow(10,(-1 * pTLevel)));
                lResponses = 0;
                lName = request.getParameter("NAME");
                lSubject = request.getParameter("SUBJECT");
                lMessage = request.getParameter("MESSAGE");
                
                //Update the response to record
                SQL = "UPDATE " + tablename + " SET Responses = Responses + 1 WHERE ID = ?";
                con2.freeformSQL(SQL, new Object[]{lRTID});
                int update = con2.updateSQL(tablename, new String[]{"Responses"}, new String[]{"Responses +1"}, "ID", lRTID);
            }
            String SQL = "INSERT INTO " + tablename +
                    " (Topic,Parent,ResponseID,TLevel,Responses,Name,Subject,Message) VALUES (?,?,?,?,?,?,?,?)";
            
            //Truncates Subject if it is more than 50 characters (database field limit)
            if(lSubject.length() > 50) {
                lSubject = lSubject.substring(0, 50);
            }

            //Convert carriage returns/line feeds into HTML breaks
            lMessage = replace(lMessage, "\r\n", "<br />");
            lMessage = replace(lMessage, "\n", "<br />");
            lMessage = replace(lMessage, "\r", "<br />");
            lMessage = replace(lMessage, "\"", "&quot;");
            lMessage = replace(lMessage, "\t", "&#09;");
            lMessage = replace(lMessage, "'", "`");

            con3.freeformSQL(SQL,new Object[]{lTopic,lParent,lResponseID,lTLevel,lResponses,lName,lSubject,lMessage});
 
            out.println("<h2>Message Posted</h2>");
            out.println("<br>");
            out.print("<p>Thank you for posting a message! ");
            out.println("<a href=\"Rl.jsp\">Click here to return to the message list.</a></p>");
            
            // Send mail to the administrators
            // sendMail(request, response, mailroot);
            //out.println("Dropping mail to: " + mailroot);

        } catch (SQLException e) {
            out.println("<h2>&nbsp;</h2>");
            out.println("<br>");
            out.println("<p>SQLException caught: " + e.getMessage() + "</p>");
        } finally {
            try {
                if (rs != null)  rs.close();
                con1.CleanUp();
                con2.CleanUp();
                con3.CleanUp();
            } catch (SQLException ignored) {}
        }
    }
    
    public void sendMail(HttpServletRequest request, HttpServletResponse response, String mailDir) {
        StringBuffer buff = new StringBuffer();
 
        String tablename = request.getParameter("tName");
        String lemailTo = request.getParameter("emailTo");
        String lemailFrom = request.getParameter("emailFrom");
        String lemailSubject = request.getParameter("emailSubject");
        String lName = request.getParameter("NAME");
        String lSubject = request.getParameter("SUBJECT");
        String lMessage = request.getParameter("MESSAGE");
               
        try {
            // Write the actual contents of the email;
            buff.append("FROM: " + lemailFrom + "\r\n");
            buff.append("TO: " + lemailTo + "\r\n");
            buff.append("SUBJECT: " + lemailSubject + "\r\n\r\n");
            
            buff.append("The message below has been posted to the ");
            buff.append(tablename.toUpperCase() + " chat room.");
            buff.append("\r\n\r\nPOSTED BY: " + lName + "\r\n");
            buff.append("SUBJECT: " + lSubject + "\r\n\r\n");
            buff.append("MESSAGE:\r\n");
            buff.append(lMessage + "\r\n");
            
            BufferedWriter out = new BufferedWriter(new FileWriter(mailDir + File.separator + "message"));
            out.write(buff.toString());
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public String replace(String str, String pattern, String replace) {
        int s = 0;
        int e = 0;
        StringBuffer result = new StringBuffer();
        
        while ((e = str.indexOf(pattern, s)) >= 0) {
            result.append(str.substring(s, e));
            result.append(replace);
            s = e+pattern.length();
        }
        result.append(str.substring(s));
        return result.toString();
    }
    
}
